<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021-03-18
 * Time: 16:51
 */

namespace app\api\home;


use \think\facade\Cache;
use think\Request;
class Login
{
    protected $urlPath = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

    public function login(Request $request)
    {
        $jscode = $request->get('jscode');

        $url = sprintf($this->urlPath,config("wechat.applet_appid"),config("wechat.applet_secret"),$jscode);

        $result = $this->https_request($url);

        $data = json_decode($result,true);

        $openid = $data['openid'];

        $token = md5(date('YmdHis'));
        Cache::set("token",$token);
        Cache::set("openID",$openid);
        echo json_encode(['openid'=>$openid,'token'=>$token]);
    }


    public static function https_request($url,$data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}